package com.seezoon.application.tcp.executor;

import com.seezoon.domain.valueobj.StatusVO;
import com.seezoon.infrastructure.constants.Constants;
import com.seezoon.infrastructure.tcp.codec.JT808;
import com.seezoon.infrastructure.tcp.common.RpcContext;
import com.seezoon.infrastructure.tcp.handler.MessageHandler;
import com.seezoon.infrastructure.tcp.jt808.JT0200;
import com.seezoon.infrastructure.tcp.jt808.JT8001;
import com.seezoon.infrastructure.tcp.jt808.JT8001.ResultCode;
import java.time.Instant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * @see JT808#位置信息汇报
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class JT0200Exe implements MessageHandler<JT0200, JT8001> {

    private final ApplicationEventPublisher publisher;

    @Override
    public int requestType() {
        return JT808.位置信息汇报;
    }

    @Override
    public int responseType() {
        return JT808.平台通用应答;
    }

    @Override
    public JT8001 execute(JT0200 request, RpcContext rpcContext) {
        JT8001 response = new JT8001();
        response.setResponseMsgSerialNo(rpcContext.getMsgSerialNo());
        response.setMsgId(rpcContext.getMsgId());
        response.setResultCode(ResultCode.SUCCESS);
        publisher.publishEvent(this.create(request, rpcContext));
        return response;
    }

    private StatusVO create(JT0200 request, RpcContext rpcContext) {
        StatusVO statusVO = new StatusVO();
        statusVO.setDeviceId(rpcContext.getClientId());
        statusVO.setLatitude((request.getLatitude() / 1000000.0d));
        statusVO.setLongitude((request.getLongitude() / 1000000.0d));
        // 当前没有
        statusVO.setSpeed(0);
        statusVO.setDirection(request.getDirection());
        statusVO.setAltitude(request.getAltitude());
        // 当前没有
        statusVO.setBatteryLevel((byte) 0);
        statusVO.setAlarmSignals(request.getWarnBit());
        statusVO.setStatusFlags(request.getStatusBit());
        statusVO.setMileage(0);
        statusVO.setStatusTime(Instant.from(Constants.DATE_TIME_JT808_FORMATTER.parse(request.getDeviceTime())));
        return statusVO;
    }
}
